package service

import (
	"github.com/TarsCloud/TarsGo/tars"
	"github.com/wzh200x/hyperNexus/hyperNexusProtocol/commonProtocol"
	"github.com/wzh200x/webServer/constants"
	Server "github.com/wzh200x/webServer/server"
)

// 模块更新请求结构
type UpdateModuleRequest struct {
	AvatarId           int32  `json:"avatarId" form:"avatarId"`                     // 角色ID
	HyperNexusAvatarId int64  `json:"hyperNexusAvatarId" form:"hyperNexusAvatarId"` // 角色HyperNexusAvatarId
	ModuleId           int32  `json:"moduleId" form:"moduleId" binding:"required"`  // 模块ID
	Data               string `json:"data" form:"data" binding:"required"`          // 模块数据
}

// 模块查询请求结构
type QueryModuleRequest struct {
	AvatarId           int32 `json:"avatarId" form:"avatarId"`                     // 角色ID
	HyperNexusAvatarId int64 `json:"hyperNexusAvatarId" form:"hyperNexusAvatarId"` // 角色HyperNexusAvatarId
	ModuleId           int32 `json:"moduleId" form:"moduleId" binding:"required"`  // 模块ID
}

// 模块响应结构
type ModuleResponse struct {
	ID                 int32  `json:"id"`                 // 模块ID
	AvatarId           int32  `json:"avatarId"`           // 角色ID
	HyperNexusAvatarId int64  `json:"hyperNexusAvatarId"` // 角色HyperNexusAvatarId
	ModuleId           int32  `json:"moduleId"`           // 模块ID
	Data               string `json:"data"`               // 模块数据
	CreateTime         string `json:"createTime"`         // 创建时间
	UpdateTime         string `json:"updateTime"`         // 更新时间
}

// UpdateModule 更新或创建角色模块数据
func UpdateModule(userID uint, username string, req UpdateModuleRequest) (*ModuleResponse, int, string) {
	// 获取DbAgentServerClient
	dbAgentClient := Server.ServerApp.DbAgentServerClient.GetClientProxy()

	// 构建查询参数
	accountQuery := commonProtocol.AccountQuery{
		AccountName: username,
	}

	// 查询账号是否存在
	account, queryErr := dbAgentClient.QueryAccount(accountQuery)
	if queryErr != nil {
		return nil, constants.ErrUnknown, "查询账号失败: " + queryErr.Error()
	}

	// 检查是否有角色
	if account.AvatarId <= 0 && account.HyperNexusAvatarId <= 0 {
		return nil, constants.ErrCharacterNotExist, "角色不存在"
	}

	// 如果请求中没有指定AvatarId或HyperNexusAvatarId，则使用账号中的值
	avatarId := req.AvatarId
	hyperNexusAvatarId := req.HyperNexusAvatarId

	if avatarId <= 0 {
		avatarId = account.AvatarId
	}

	if hyperNexusAvatarId <= 0 {
		hyperNexusAvatarId = account.HyperNexusAvatarId
	}

	// 先尝试查询模块是否存在
	moduleQuery := commonProtocol.AvatarModuleQuery{
		AccountName:        username,
		AvatarId:           avatarId,
		HyperNexusAvatarId: hyperNexusAvatarId,
		ModuleId:           req.ModuleId,
	}

	_, queryErr = dbAgentClient.QueryAvatarModule(moduleQuery)

	// 如果模块不存在，则创建新模块
	if queryErr != nil {
		// 账号不存在，创建新账号
		if queryErr.Error() == "record not found" {
			// 创建模块
			moduleCreate := commonProtocol.AvatarModuleCreate{
				AccountName:        username,
				AvatarId:           avatarId,
				HyperNexusAvatarId: hyperNexusAvatarId,
				ModuleId:           req.ModuleId,
				Data:               req.Data,
			}

			createdModule, createErr := dbAgentClient.CreatAvatarModule(moduleCreate)
			if createErr != nil {
				tars.GetLogger("").Errorf("创建角色模块失败: %v", createErr)
				return nil, constants.ErrUnknown, "创建角色模块失败: " + createErr.Error()
			}

			// 转换为响应结构
			response := &ModuleResponse{
				ID:                 createdModule.ID,
				AvatarId:           createdModule.AvatarId,
				HyperNexusAvatarId: createdModule.HyperNexusAvatarId,
				ModuleId:           createdModule.ModuleId,
				Data:               createdModule.Data,
				CreateTime:         createdModule.CreateTime,
				UpdateTime:         createdModule.UpdateTime,
			}

			return response, 0, ""
		}
		return nil, constants.ErrCharacterModuleUpdate, "角色模块查询失败: " + queryErr.Error()
	}

	// 更新模块
	moduleUpdate := commonProtocol.AvatarModuleUpdate{
		AccountName:        username,
		AvatarId:           avatarId,
		HyperNexusAvatarId: hyperNexusAvatarId,
		ModuleId:           req.ModuleId,
		Data:               req.Data,
	}

	updatedModule, updateErr := dbAgentClient.UpdateAvatarModule(moduleUpdate)
	if updateErr != nil {
		tars.GetLogger("").Errorf("更新角色模块失败: %v", updateErr)
		return nil, constants.ErrUnknown, "更新角色模块失败: " + updateErr.Error()
	}

	// 转换为响应结构
	response := &ModuleResponse{
		ID:                 updatedModule.ID,
		AvatarId:           updatedModule.AvatarId,
		HyperNexusAvatarId: updatedModule.HyperNexusAvatarId,
		ModuleId:           updatedModule.ModuleId,
		Data:               updatedModule.Data,
		CreateTime:         updatedModule.CreateTime,
		UpdateTime:         updatedModule.UpdateTime,
	}

	return response, 0, ""
}

// QueryModule 查询角色模块数据
func QueryModule(userID uint, username string, req QueryModuleRequest) (*ModuleResponse, int, string) {
	// 获取DbAgentServerClient
	dbAgentClient := Server.ServerApp.DbAgentServerClient.GetClientProxy()

	// 构建查询参数
	accountQuery := commonProtocol.AccountQuery{
		AccountName: username,
	}

	// 查询账号是否存在
	account, queryErr := dbAgentClient.QueryAccount(accountQuery)
	if queryErr != nil {
		return nil, constants.ErrUnknown, "查询账号失败: " + queryErr.Error()
	}

	// 检查是否有角色
	if account.AvatarId <= 0 && account.HyperNexusAvatarId <= 0 {
		return nil, constants.ErrCharacterNotExist, "角色不存在"
	}

	// 如果请求中没有指定AvatarId或HyperNexusAvatarId，则使用账号中的值
	avatarId := req.AvatarId
	hyperNexusAvatarId := req.HyperNexusAvatarId

	if avatarId <= 0 {
		avatarId = account.AvatarId
	}

	if hyperNexusAvatarId <= 0 {
		hyperNexusAvatarId = account.HyperNexusAvatarId
	}

	// 查询模块
	moduleQuery := commonProtocol.AvatarModuleQuery{
		AccountName:        username,
		AvatarId:           avatarId,
		HyperNexusAvatarId: hyperNexusAvatarId,
		ModuleId:           req.ModuleId,
	}

	module, queryErr := dbAgentClient.QueryAvatarModule(moduleQuery)
	if queryErr != nil {
		tars.GetLogger("").Errorf("查询角色模块失败: %v", queryErr)
		return nil, constants.ErrUnknown, "查询角色模块失败: " + queryErr.Error()
	}

	// 转换为响应结构
	response := &ModuleResponse{
		ID:                 module.ID,
		AvatarId:           module.AvatarId,
		HyperNexusAvatarId: module.HyperNexusAvatarId,
		ModuleId:           module.ModuleId,
		Data:               module.Data,
		CreateTime:         module.CreateTime,
		UpdateTime:         module.UpdateTime,
	}

	return response, 0, ""
}
